package com.ruoyi.web.utils.influxdb;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.CommonUtils;
import lombok.val;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc  封装InfluxDB数据对象
 * @author fwx 2023/11/4 14:34
 **/
public class DeviceData {

    Map<String,Object> dataMap = new HashMap<>();

    private LocalDateTime dataTime;

    private String dataTimeStr;

    public DeviceData(Map<String, Object> dataMap) {
        this.dataMap = dataMap;
    }

    public DeviceData() {
    }

    public DeviceData(FluxRecord record) {

        //TODO

//        if(record == null){
//            return;
//        }
//
//        this.dataMap = record.getValues();
//
//        if(record.getTime() != null){
//            this.setDataTime(CommonUtils.getLocalDateTime(record.getTime()));
//        }
//
//        this.dataMap.remove("result");
//        this.dataMap.remove("table");
//        this.dataMap.remove("_start");
//        this.dataMap.remove("_stop");
//        this.dataMap.remove("_field");
//        this.dataMap.remove("_measurement");
    }


    public Object get(String key){
        return dataMap.get(key);
    }

    public Double getDouble(String key){
        if(dataMap.get(key) == null){
            return null;
        }

        return Double.parseDouble(dataMap.get(key).toString());
    }

    public Double getValue(){

        if(dataMap.get("_value") == null){
            return null;
        }

        double value = Double.parseDouble(dataMap.get("_value").toString());
        value =  Math.round(value * 10) / 10.0;  //保留一位小数
        return value;
    }

    public Double getBaseValue(String key){

        if(dataMap.get("_value") == null){
            return null;
        }

        JSONObject json = JSONObject.parseObject(dataMap.get("_value").toString());
        return json.getDouble(key);
    }

    public LocalDateTime getDataTime() {
        return dataTime;
    }

    public void setDataTime(LocalDateTime dataTime) {
        this.dataTime = dataTime;
        this.dataTimeStr = DateUtil.format(dataTime, DatePattern.NORM_DATETIME_PATTERN);
    }

    public String getDataTimeStr() {
        return dataTimeStr;
    }

    public String getDataDateStr() {
        return DateUtil.format(dataTime, DatePattern.NORM_DATE_PATTERN);
    }


    public void setDataTimeStr(String dataTimeStr) {
        this.dataTimeStr = dataTimeStr;
    }

    @Override
    public String toString() {
        return "DeviceData{" +
                "dataMap=" + dataMap +
                ", dataTime=" + dataTime +
                ", dataTimeStr='" + dataTimeStr + '\'' +
                '}';
    }
}
